package com.ainote.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.util.*;

@RestController
@RequestMapping("/api/upload")
public class UploadController {

    @Value("${asr.baidu.temp_dir:./uploads/temp}")
    private String tempDir;

    @Value("${asr.baidu.merge_dir:./uploads/merge}")
    private String mergeDir;

    @PostMapping("/chunk")
    public Map<String, Object> uploadChunk(
            @RequestParam("file") MultipartFile file,
            @RequestParam("fileId") String fileId,
            @RequestParam("index") int index
    ) throws IOException {

        File chunkDir = new File(tempDir, fileId);
        if (!chunkDir.exists()) chunkDir.mkdirs();

        File chunkFile = new File(chunkDir, "chunk_" + index);
        file.transferTo(chunkFile);

        return Map.of("status", "ok", "index", index);
    }

    @PostMapping("/merge")
    public Map<String, Object> mergeChunks(@RequestBody Map<String, String> body) throws IOException {
        String fileId = body.get("fileId");
        String filename = body.get("filename");

        File chunkDir = new File(tempDir, fileId);
        if (!chunkDir.exists()) throw new IOException("未找到分片目录: " + chunkDir);

        File mergedDir = new File(mergeDir);
        if (!mergedDir.exists()) mergedDir.mkdirs();

        File mergedFile = new File(mergedDir, filename);

        try (FileOutputStream fos = new FileOutputStream(mergedFile)) {
            File[] chunks = chunkDir.listFiles((dir, name) -> name.startsWith("chunk_"));
            if (chunks == null || chunks.length == 0) throw new IOException("没有找到分片文件");

            Arrays.sort(chunks, Comparator.comparingInt(f -> Integer.parseInt(f.getName().split("_")[1])));

            byte[] buffer = new byte[8192];
            for (File chunk : chunks) {
                try (FileInputStream fis = new FileInputStream(chunk)) {
                    int len;
                    while ((len = fis.read(buffer)) != -1) {
                        fos.write(buffer, 0, len);
                    }
                }
            }
        }

        // 删除临时分片
        for (File f : Objects.requireNonNull(chunkDir.listFiles())) f.delete();
        chunkDir.delete();

        return Map.of(
                "status", "merged",
                "path", mergedFile.getAbsolutePath(),
                "url", "/uploads/merge/" + filename
        );
    }
}
